const express = require("express")
const app = express()

app.all("*", function (req, res, next) {
  //设置允许跨域的域名，*代表允许任意域名跨域
  res.header("Access-Control-Allow-Origin", "*")
  //允许的header类型
  res.header("Access-Control-Allow-Headers", "content-type")
  //跨域允许的请求方式
  res.header("Access-Control-Allow-Methods", "DELETE,PUT,POST,GET,OPTIONS")
  if (req.method.toLowerCase() == "options") res.send(200)
  //让options尝试请求快速结束
  else next()
})
app.use(express.static("public"))
const { HOST, PORT } = require("./config.json")
const word_controller = require("./controllers/wordController")
const sentence_controller = require("./controllers/sentenceController")
const paragraph_controller = require("./controllers/paragraphController")
// const image_controller = require("./controllers/imageController")
const music_controller = require("./controllers/musicController")

app.get("/", (req, res) => {
  // 加载index.html
  res.sendFile(__dirname + "/index.html")
})

// 生成随机词语 句子 段落
app.get(/\/(\d+)(?:w|word|words)(,*)$/, word_controller.word)
app.get(/\/(\d+)(?:s|sentence|sentences)(,*)$/, sentence_controller.sentence)
app.get(
  /\/(\d+)(?:p|paragraph|paragraphs)(,*)$/,
  paragraph_controller.paragraph
)
app.get(/\/(\d+)(?:c|chinese|china)$/, word_controller.wordChinese)

// 生成随机占位图片
// app.get(
//   /\/(\d+)(?:x|\*|X)(\d+)\.(jpg|jpeg|png)(?:,([a-zA-Z0-9]+?),([a-zA-Z0-9]+?))*$/,
//   image_controller.image
// )
// app.get(/\/(\d+)(?:x|\*|X)(\d+)$/, image_controller.imageRandom)

app.get("/music", music_controller.music)
app.listen(PORT, HOST, () => {
  console.log(`run http://${HOST}:${PORT}`)
})
